package com.feihong.yw189.activity.kaika;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.ImageButton;

import com.feihong.yw189.R;
import com.feihong.yw189.activity.base.BaseActivity;
import com.feihong.yw189.global.RequestTools;
import com.feihong.yw189.message.LoginMessage;

import java.util.ArrayList;

import me.dm7.barcodescanner.zbar.BarcodeFormat;
import me.dm7.barcodescanner.zbar.Result;
import me.dm7.barcodescanner.zbar.ZBarScannerView;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

/**
 * Created by  on 2017/6/29..
 * 扫sim卡
 */
@RuntimePermissions
public class SannerActivity extends BaseActivity implements ZBarScannerView.ResultHandler {
    private ZBarScannerView mScannerView;
    private boolean isNeeds = true;
    //保持长亮
    PowerManager powerManager = null;
    PowerManager.WakeLock wakeLock = null;

    private ImageButton btn_back;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //保持长亮
        powerManager = (PowerManager) this.getSystemService(Activity.POWER_SERVICE);
        wakeLock = this.powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Lock");
        setContentView(R.layout.activity_scanner);
        mScannerView = (ZBarScannerView) findViewById(R.id.mZXingScannerView);

        btn_back = (ImageButton) findViewById(R.id.scanner_iv_back);
        btn_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        // mScannerView = new ZXingScannerView(SannerActivity.this);   // Programmatically initialize the scanner view
        ArrayList<BarcodeFormat> list = new ArrayList<>();
        list.add(BarcodeFormat.QRCODE);
        //二维码
        // setContentView(mScannerView);                // Set the scanner view as the content view
        SannerActivityPermissionsDispatcher.NeedsPermissionWithCheck(this);
    }

    @Override
    public void setTheme() {
        isDrakFont = false;
    }

    @Override
    public void onResume() {
        super.onResume();

        //保持长亮
        wakeLock.acquire();

        if (mScannerView != null && isNeeds) {
            mScannerView.resumeCameraPreview(SannerActivity.this);
        }
       // mScannerView.setBorderLineLength(20);

    }
    public boolean isCameraUseable() {
        boolean canUse = true;
        Camera mCamera = null;
        try {
            mCamera = Camera.open();
            // setParameters 是针对魅族MX5。MX5通过Camera.open()拿到的Camera对象不为null
            Camera.Parameters mParameters = mCamera.getParameters();
            mCamera.setParameters(mParameters);
        } catch (Exception e) {
            canUse = false;
        }
        if (mCamera != null) {
            mCamera.release();
        }
        return canUse;
    }

    private void openCamera() {
        if (isNeeds) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    mScannerView.setResultHandler(SannerActivity.this); // Register ourselves as a handler for scan results.
                    try {
                        mScannerView.startCamera();
                        // Start camera on resume

                    } catch (Exception ex) {
                        ex.printStackTrace();
                        showErrorDialog("权限不足", "您没有开启次应用的使用摄像头权限。请到系统设置-->权限管理 开启摄像使用权限。如果您的手机上安装了第三方管家应用（360管家，腾讯管家等），请开启一下摄像头权限！", new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
                                finish();
                            }
                        });
                    }
                }
            }, 200);
        } else {
            showErrorDialog("权限不足", "您没有开启次应用的使用摄像头权限。请到系统设置-->权限管理 开启摄像使用权限。如果您的手机上安装了第三方管家应用（360管家，腾讯管家等），请开启一下摄像头权限！", new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    finish();
                }
            });
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        mScannerView.stopCamera();           // Stop camera on pause
        //释放常亮
        wakeLock.release();
    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {
    }

    //扫码返回结果
    @Override
    public void handleResult(final Result result) {
        // Do something with the result here
        if (result != null && result.getContents() != null) {
            Intent intent = new Intent();
            intent.putExtra("result", result.getContents());
            setResult(1, intent);
            finish();
        }
/*
//        showErrorDialog("扫码成功", result.getContents(), new DialogInterface.OnDismissListener() {
//            @Override
//            public void onDismiss(DialogInterface dialog) {
//                mScannerView.resumeCameraPreview(SannerActivity.this);
//            }
//        });*/
    }

    @Override
    protected void onDestroy() {
        RequestTools.removeRequest(SannerActivity.class.getName());
        super.onDestroy();
    }
    @NeedsPermission(Manifest.permission.CAMERA)
    void NeedsPermission() {

        isNeeds = true;
        openCamera();
    }

    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        SannerActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale(Manifest.permission.CAMERA)
    void ShowRationale(final PermissionRequest request) {
        new AlertDialog.Builder(this)
                .setPositiveButton("允许", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        request.proceed();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(@NonNull DialogInterface dialog, int which) {
                        request.cancel();
                    }
                })
                .setCancelable(false)
                .setMessage("请允许获取相机权限")
                .show();
    }

    @OnPermissionDenied(Manifest.permission.CAMERA)
    void PermissionDenide() {
        isNeeds = false;
        showErrorDialog("权限不足", "您没有开启次应用的使用摄像头权限。请到系统设置-->权限管理 开启摄像使用权限。如果您的手机上安装了第三方管家应用（360管家，腾讯管家等），请开启一下摄像头权限！", new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                finish();
            }
        });
    }

    @OnNeverAskAgain(Manifest.permission.CAMERA)
    void NeverAskAgin() {
        isNeeds = false;
        showErrorDialog("权限不足", "您没有开启次应用的使用摄像头权限。请到系统设置-->权限管理 开启摄像使用权限。如果您的手机上安装了第三方管家应用（360管家，腾讯管家等），请开启一下摄像头权限！", new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                finish();
            }
        });
    }
}
